package com.dudu.controller;

import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.dudu.bean.IfControlBean;
import com.dudu.bean.IfControlRuleBean;
import com.dudu.bean.UserBean;
import com.dudu.service.IInfoControl;
import com.dudu.service.impl.InfoControlServiceImpl;
import com.dudu.utils.HttpRequest;

import core.CoreService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 信控控制类
 * @author zx
 *
 */
public class InfoControlController extends CoreService implements IInfoControlController {

	private final String KEY_CURRENT_USER = "key_current_user";

	private static IInfoControl serviceControl = new InfoControlServiceImpl();

	private static final Logger log = Logger.getLogger(InfoControlController.class.getSimpleName());
    
	/**
	 * 上行短信反馈审核结果后回调处理
	 */
	@Override
	public String infoControlFeedback() {
		JSONObject retJson = new JSONObject();
		String receiveData = null;
		JSONObject receiveJson = null;
		JSONArray recordDataArrray = null;
		boolean success=false;
		try {
			// 从流中获取参数
			InputStream inStream = this.getRequest().getInputStream();
			byte[] data = HttpRequest.readStream(inStream);
			if (data != null) {
				receiveData = new String(data, "utf-8");
				if (StringUtils.isEmpty(receiveData)) {
					retJson.put("result", "0001");
					retJson.put("describe", "上行短信数据为空");
				} else {
					receiveJson = JSONObject.fromObject(receiveData);
					recordDataArrray = receiveJson.getJSONArray("data");// 话单数据
					if (recordDataArrray == null || recordDataArrray.isEmpty()) {
						retJson.put("result", "0002");
						retJson.put("describe", "上行短信数据data节点为空");
					} else {
						success=true;
						retJson.put("result", "0");
						retJson.put("describe", "上行短信数据接收成功");
					}
				}
			}
		} catch (Exception e) {  
			e.printStackTrace();
			log.error("解析上行短信数据发生异常", e);
			retJson.put("code", "0010");
			retJson.put("desc", "接收方解析数据发生异常");
		}
		/**
		 * 数据接收成功
		 */
		if(success){
			try{
				for (int i = 0; i < recordDataArrray.size(); i++) {
					JSONObject feedback = (JSONObject) recordDataArrray.get(i);
					int id = feedback.getInt("msg_id");
					IfControlBean ifBean=serviceControl.queryIfControlById(id);
					String custAccount = feedback.getString("cust_account");
					String appKey = feedback.getString("app_key");
					String checkConclusion = feedback.getString("content");
					String checker = feedback.getString("moblie");
					IfControlBean bean = new IfControlBean();
					bean.setId(id);
					bean.setChecker(checker);
					bean.setCustAccount(custAccount);
					bean.setAppKey(appKey);
					bean.setCheckConclusion(checkConclusion);
					bean.setStatus("1");// 审核完成
					bean.setAbilityType(ifBean.getAbilityType());
					bean.setBatchNumber(ifBean.getBatchNumber());
					bean.setProductCode(ifBean.getProductCode());
					serviceControl.infoControlSMSFeedback(bean);
				}
			}catch(Exception e){
				e.printStackTrace();
				log.error("上行短信回复处理错误", e);
			}
		}
		// 响应数据
		return returnData(retJson.toString());
	}
    
	/**
	 * 查询信控规则列表
	 */
	@Override
	public String queryInfoControlRules() {
		List<JSONObject> rules = null;
		// 最后返回的对象
		JSONObject object = new JSONObject();
		// 放在JSONObject里面的数据对象
		JSONArray jsonArray = new JSONArray();
		// 获取当前登录用户信息
		UserBean currentUser = (UserBean) this.getSession().getAttribute(KEY_CURRENT_USER);
		// 判断如果用户信息不为空则继续下一步
		if (currentUser != null) {
			// 获取页面分页用信息
			String pageSql = this.getPageSql();
			// 查询数据
			rules = serviceControl.queryAllInfoControlRules(pageSql);
			// 查询总数量
			int totalAcount = serviceControl.queryALLIfControlRulesCount();
			// 将查询的数据转化为json格式
			jsonArray = JSONArray.fromObject(rules);
			JSONObject dataobject = new JSONObject();
			// 总数量信息
			dataobject.put("totalItemNum", totalAcount);
			// 具体数据信息
			dataobject.put("items", jsonArray);
			object.put("data", dataobject);
			object.put("flag", "000000");
			object.put("desc", "success");
		} else {
			object.put("flag", "100000");
		}
		return returnData(object.toString());
	}
    
	/**
	 * 创建新的信控规则
	 */
	@Override
	public String createInfoControlRule() {
		HttpServletRequest request=this.getRequest();
		// 最后返回的对象
		JSONObject object = new JSONObject();
		// 获取当前登录用户信息
		UserBean currentUser = (UserBean) this.getSession().getAttribute(KEY_CURRENT_USER);
		// 判断如果用户信息不为空则继续下一步
		if (currentUser != null) {
            String bean = (String) request.getParameter("data");
            JSONObject data = JSONObject.fromObject(bean);
            IfControlRuleBean ruleBean=(IfControlRuleBean) JSONObject.toBean(data, IfControlRuleBean.class);
			ruleBean.setUseFlag("yes");
			ruleBean.setCreateUser(currentUser.getAccount());
			serviceControl.createIfControlRule(ruleBean);
			object.put("flag", "000000");
			object.put("desc", "success");
		} else {
			object.put("flag", "100000");
		}
		return returnData(object.toString());	
	}
    
	/**
	 * 查询信控核查人员
	 */
	@Override
	public String queryCheckers() {
		JSONObject object = new JSONObject();
		// 获取当前登录用户信息
		UserBean currentUser = (UserBean) this.getSession().getAttribute(KEY_CURRENT_USER);
		// 判断如果用户信息不为空则继续下一步
		if (currentUser != null) {
			String checkers=serviceControl.queryCheckers();
			object.put("flag", "000000");
			object.put("desc", "success");
			object.put("data", checkers);
		}else {
			object.put("flag", "100000");
		}
		return returnData(object.toString());	
	}
    
	/**
	 * 更新信控规则
	 */
	@Override
	public String updateInfoControlRule() {
		JSONObject object = new JSONObject();
		// 获取当前登录用户信息
		UserBean currentUser = (UserBean) this.getSession().getAttribute(KEY_CURRENT_USER);
		// 判断如果用户信息不为空则继续下一步
		if (currentUser != null) {
            String bean = (String) this.getRequest().getParameter("data");
            JSONObject data = JSONObject.fromObject(bean);
            IfControlRuleBean ruleBean=(IfControlRuleBean) JSONObject.toBean(data, IfControlRuleBean.class);
			ruleBean.setUpdateUser(currentUser.getAccount());
			int updateResult=serviceControl.updateIfControlRule(ruleBean);
			object.put("flag", "000000");
			object.put("desc", "success");
			object.put("result", updateResult);
		}else {
			object.put("flag", "100000");
		}
		return returnData(object.toString());	
	}
    
	/**
	 * 启用/停用信控规则
	 */
	@Override
	public String updateInfoControlRuleStatus() {
		JSONObject object = new JSONObject();
		// 获取当前登录用户信息
		UserBean currentUser = (UserBean) this.getSession().getAttribute(KEY_CURRENT_USER);
		// 判断如果用户信息不为空则继续下一步
		if (currentUser != null) {
            String bean = (String) this.getRequest().getParameter("data");
            JSONObject data = JSONObject.fromObject(bean);
            IfControlRuleBean ruleBean=(IfControlRuleBean) JSONObject.toBean(data, IfControlRuleBean.class);
			ruleBean.setUpdateUser(currentUser.getAccount());
			int updateResult=serviceControl.updateIfControlRuleStatus(ruleBean);
			object.put("flag", "000000");
			object.put("desc", "success");
			object.put("result", updateResult);
		}else {
			object.put("flag", "100000");
		}
		return returnData(object.toString());	
	}

}
